package cn.wdm.ymcc.mq;

import cn.wdm.ymcc.domain.CourseOrder;
import cn.wdm.ymcc.dto.PayNotifyDto;
import cn.wdm.ymcc.service.ICourseOrderService;
import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;


@Component
@RocketMQMessageListener(
        consumerGroup="order-notify-consummer",
        topic="asynnotifymsg-topic",
        selectorExpression="asynnotifymsg-tag",
        messageModel= MessageModel.BROADCASTING //默认是集群模式，一个消息只会被一个消费者消费
)
/**
 * 支付成功通知给order微服务
 * 支付宝成功异步通知 消费投递在mq中的消息，修改订单的状态。
 * MessageExt 里面是要消费的消息Message PayNotifyDto
 */
public class PaySuccessNotify2OrderConsummer implements RocketMQListener<MessageExt> {
    @Autowired
    private ICourseOrderService courseOrderService;
    @Override
    public void onMessage(MessageExt messageExt) {
        byte[] bytes = messageExt.getBody();
        //1.非空校验
        if(bytes==null||bytes.length==0){
            return;//为空，直接签收
        }
        String str = new String(bytes, StandardCharsets.UTF_8);
        PayNotifyDto payNotifyDto = JSONObject.parseObject(str, PayNotifyDto.class);
        //2支付成功回调 我们平台，修改支付单的状态
        //2.1 根据订单号查出订单
        CourseOrder courseOrder = courseOrderService.selectOrderByOrderNo(payNotifyDto.getOrderNo());
        if(courseOrder==null){
            return;
        }
        //2.2 如果订单的状态为待支付才修改状态
        if(courseOrder.getStatusOrder().intValue()==0){
            courseOrderService.updateOrderState(courseOrder);
        }
    }
}
